import * as React from 'react';
import { observer, inject } from 'mobx-react';
import { ChatStore } from '../../store/ChatStore';
import SendBoard from '../../component/sendBoard/SendBoard';
import { MessageItem, DrawerType, ChatGrOrFrType, ChatItem, ChatUserType } from '../../interface/IChat';
import webIM from '../../net/WebIM';
import { MessageType, mentionsAllKey } from '../../net/Const';
import message from 'antd/es/message';
import DrawerDetail from './DrawerDetail';
import { FriendStore } from '../../store/FriendStore';
import { IconImgEdit } from '../../component/iconImage/IconImageEdit';
import { AvatorWithPhoto } from '../../component/avatorWithPhoto/AvatorWithPhoto';
import { GroupStore } from '../../store/GroupStore';
import { Department, GroupMemRole, VirualEmployee } from '../../interface/IGroup';
import { autorun, IReactionDisposer, reaction } from 'mobx';
import { MessageList } from '../../component/messageList/MessageList';
import systemStore, { SystemStore } from '../../store/SystemStore';
import TransmitSelectModal from '../../component/transmitSelectModal/TransmitSelectModal';
import { SelectItemType } from '../../interface/ITransmit';
import { MesListModal } from '../../component/mesListModal.tsx/MesListModal';
import Utils from '../../utils/utils';
import Icon from 'antd/es/icon';
import { isOpenIntegration } from '../../config/SystemConfig';
import ipcRender from '../../ipcRender';
import { chatContentCber, callBackServicetype } from '../../service/chatContentService';
import { Input, Modal, Popover, Select, Spin, Tabs, Tag, Tooltip } from 'antd';
import SvgIcon from '../../component/svgIcon/SvgIcon';
import TextArea from 'antd/es/input/TextArea';
import './ChatDetail.less'
import ResizeBar from '../../component/resizeBar/ResizeBar';
import InputQuickEditor from '../../component/inputQuickEditor/InputQuickEditor';
import { TagGroupStore } from '../../store/TagGroupStore';
import TagSelector from '../../component/tagSelector/TagSelector';
import TagViewer from '../../component/tagViewer/TagViewer';
import { UserType } from '../../const/index';
import imsdk from '../../net/IMSDK';
import SelectService from '../../component/selectService/SelectService';
const { TabPane } = Tabs;


export interface IChatDetailProps { }
interface IChatDetailPropsWithStore extends IChatDetailProps {
	chatStore: ChatStore;
	friendStore: FriendStore;
	groupStore: GroupStore;
	tagGroupStore:TagGroupStore,
	systemStore:SystemStore,
}
interface MentionPeople {
	name: string;
	memId: string;
}
export interface IChatDetailState {
	chatSetting: boolean;
	mentionPeople: MentionPeople[];
	chatId: string;
	idWithTag:string,
	chatInfo:ChatItem
	remark?:string,
	showSelectChatModal: boolean;
	showMenu: boolean;
	listForceScroll: number;
	getMesLoading: boolean,
	// 是否在编辑标签组
	editingTagGroup:boolean
	tagsGroup:string[],
	// 显示转接列表
	showTransCallList:boolean;
	showTransCallListKey?:string;
	/**
	 * 是否在服务中
	 */
	isInservicing:boolean
	transUserId?:number,
	transUserRemark?:string,
	refreshKey?:string,
	extendInfo?:any
}

@inject('chatStore', 'friendStore', 'groupStore','tagGroupStore','systemStore')
@observer
export default class ChatDetail extends React.Component<IChatDetailProps, IChatDetailState> {
	constructor(props: IChatDetailProps) {
		super(props);
		const { chatStore, groupStore, tagGroupStore } = this.injected;
		const dataChat = chatStore.currentChatData;

		this.state = {
			chatSetting: false,
			mentionPeople: [],
			chatId: (this.props as IChatDetailPropsWithStore).chatStore.currentChatData.id,
			idWithTag:(this.props as IChatDetailPropsWithStore).chatStore.currentChatData.idWithTag,
			chatInfo: {...(this.props as IChatDetailPropsWithStore).chatStore.currentChatData },
			refreshKey:{...(this.props as IChatDetailPropsWithStore).chatStore.currentChatData }.refreshKey,
			showSelectChatModal: false,
			// imgurl: systemStore.backImageurl? systemStore.backImageurl:'',
			showMenu: false,
			listForceScroll: 0,
			getMesLoading: false,
			editingTagGroup:false,
			remark: this.chatDetail.remark,
			//
			tagsGroup:[],
			showTransCallList:false,
			showTransCallListKey:Math.random()+'',
			isInservicing:true,
			extendInfo: dataChat.extendInfo ||{}
		};
		this.refMessageBodyUserInfo = React.createRef();
	}
	refMessageBodyUserInfo
	get chatDetail() {
		return this.injected.chatStore.currentChatData.extendInfo || {}
	}
	updateChatDetail( name,value ){
		const info = this.injected.chatStore.currentChatData.extendInfo;
		if( info ){
			info[name] = value;
		}
		this.setState({
			extendInfo:{...this.state.extendInfo, [name]:value},
		})
		this.updateChatRemark({
			userId:this.chatDetail.userId,
			[name]:value
		})
	}
	// shouldComponentUpdate() {
	//   return false;
	// }

	get injected() {
		return this.props as IChatDetailPropsWithStore;
	}
	isUserService(){
		
		return Utils.isUserService(this.state.chatId);
	}
	canTransCall(){
		const chatInfo = this.state.chatInfo.extendInfo ? this.state.chatInfo.extendInfo : {}
		const user = this.injected.systemStore.user;
		if( this.isGroup()){
			return false;
		}
		/** 企业帐号有转接功能 */
		if( user.userType == UserType.Enterprise ){
			// 聊天目标不是客服，并聊天目标不是自己
			const cantTransType = [ UserType.Enterprise, UserType.Public].includes(chatInfo.userType)
			if( cantTransType ){
				return false;
			}
			if( user.userId!= chatInfo.userId ){
				return true;
			}
		}
		if( !this.state.isInservicing ){
			return false;
		}
		return false;
	}
	showInfo(){
		const user = this.injected.systemStore.user;
		const chatInfo = this.state.chatInfo.extendInfo ? this.state.chatInfo.extendInfo : {}
		if( typeof chatInfo.showUserInfo!='undefined' && !chatInfo.showUserInfo){
			// 运后后台禁用显示此信息面板
			return false;
		}
		if( user.userType == UserType.Enterprise){
			return true;
		}
		if( !this.isUserService()){
			return false;
		}
		return false;
	}
	send = (content: string, chatId: string) => {
		if (!content) {
			message.warn('不能发送空内容');
			return;
		}
		let chart = this.injected.chatStore;
		const chatItem = chart.chats.find((item) => item.id == chatId);
		// console.log('发送的消息', chatItem);


		let sendMentions = this.state.mentionPeople.filter(item => content.indexOf(`@${item.name}`)>-1)

		if (chatItem) {
			const _msgData = {
				type: chart.isReply ? 94 : MessageType.TEXT,
				content,
				toUserId: chatId,
				toUserName: chatItem ? chatItem.name : chart.currentChat.id == chatId ? chart.currentChat.name : ''
			};
			let mentionIds = sendMentions.map(item => item.memId).join(',')
			if (sendMentions.length > 0&& isOpenIntegration) {
				//群管理或群主管理群积分
				chart.setIntegration(content, sendMentions, mentionIds);
			}

			const msg = webIM.createMessage(_msgData.type, _msgData.content, _msgData.toUserId, _msgData.toUserName);
			if (mentionIds) {
				msg.objectId = mentionIds;
			}
			if (chatItem) {
				msg.isReadDel = chatItem.snapChat;
			}
			if (chart.isReply) {
				msg.objectId = JSON.stringify(chart.replyMessage);
				// console.log(msg.objectId,'转换后的消息体')
			}
			webIM.sendMessage(msg, '');
			// console.log(msg,'发出的消息是什么?????????????',msg.to,msg.toJid,msg.toUserId,msg.toUserName)
			// msg.fromUserName = chart.currentChatData.nickname ? chart.currentChatData.nickname : msg.fromUserName;
			this.injected.chatStore.addMessage(chatId, msg, true);
			// console.log(this.injected.chatStore.messageData.get(chatId),'消息体里的数据')
			this.updateChatData(msg.content, msg.timeSend);
			if (Array.isArray(sendMentions) && sendMentions.length > 0) {
				this.setState({
					mentionPeople: []
				})
			}
			//todo 测试用
			// this.sendAllMsg();
			this.scrollToBottom();
		}

	};

	// sendAllMsg = () =>{

	// 	this.injected.groupStore.groupList.forEach((member, index) =>{
	// 		let msg = webIM.createMessage(1,member.name + ` ${index}`,member.id);
	// 		console.log('gaga---',index);

	// 		webIM.sendMessage(msg,'');
	// 	})
	// 	this.injected.friendStore.friendList.forEach((friend, index) =>{
	// 		let msg = webIM.createMessage(1,friend.toNickname + ` ${index}`,friend.userId+'');
	// 		console.log('hahahahhahahahahah---',index);
	// 		webIM.sendMessage(msg,'');
	// 	})

	// }


	//发送失败的消息，修改休息消息状态，再发一遍消息即可
	reSendMes = (msg: MessageItem) => {
		this.injected.chatStore.selMesWithLocal(msg);
		let chart = this.injected.chatStore;
		const newMsg = { ...msg, timeSend: webIM.getServerTime() + '' }
		this.injected.chatStore.setMessageLoading(newMsg.messageId);
		this.injected.chatStore.addMessage(chart.currentChatData.id, newMsg, true);
		webIM.sendMessage(newMsg, '', true);
	};
	showChatSetting = (isGroup: boolean) => {
		if (isGroup) {
			this.drawerType = DrawerType.group;
		} else {
			this.drawerType = DrawerType.friend;
		}
		this.setState({
			chatSetting: true
		});
	};
	onClose = () => {
		this.setState({
			chatSetting: false
		});
	};
	//更新聊天列表 最新消息及最新时间
	updateChatData = (content: string, time: string) => {
		this.injected.chatStore.updateMes(content, time);
	};
	updateChatRemark = ( body : any) => {
		this.injected.chatStore.updateChatRemark(body);	
	}
	showChatNotice = () => {
		this.drawerType = DrawerType.notice;
		
		this.setState({
			chatSetting: true
		});
	};
	autoFun: IReactionDisposer;
	disposeReaction:any;
	componentDidMount() {
		
		this.scrollToBottom();
		this.autoFun = autorun(() => {
			if (this.injected.chatStore.currentChatData.type == ChatGrOrFrType.group) {
				this.injected.groupStore.updataSingleGroupList();
			}
			
		});
		const { chatStore } = this.injected
		const dataChat = chatStore.currentChatData
		this.setState({
			tagsGroup:(dataChat.tagGroups||[]).map(item=> item.name)
		})
		// 监听currentChatData变化
		this.disposeReaction = reaction(
			() => this.injected.chatStore.currentChatData,
			(chatItem) => {
				// 不灵
				console.log('chatStore 发生变化:', chatItem);
				// const dataChat = chatStore.currentChatData;
				// let tagsGroup = (chatItem.tagGroups||[]).map(item=> item.name)
				// debugger;
				// this.setState({
				// 	tagsGroup:(chatItem.tagGroups||[]).map(item=> item.name)
				// })
				// 在这里执行你想要的副作用
			}
		);

	}

	componentWillUnmount() {
		this.autoFun && this.autoFun();
		this.disposeReaction && this.disposeReaction();
	}
	getNextProps = (props: IChatDetailProps) => {
		return props as IChatDetailPropsWithStore;
	};
	static getDerivedStateFromProps(nextProps: IChatDetailProps, prevState: IChatDetailState) {
		const storeProps = nextProps as IChatDetailPropsWithStore
		const chatData:any = storeProps.chatStore.currentChatData ||{}
		if (storeProps.chatStore.currentChatData.id != prevState.chatId || storeProps.chatStore.currentChatData.refreshKey != prevState.refreshKey) {
			return {
				
				chatId: (nextProps as IChatDetailPropsWithStore).chatStore.currentChatData.id,
				idWithTag:(nextProps as IChatDetailPropsWithStore).chatStore.currentChatData.idWithTag,
				chatInfo: {...(nextProps as IChatDetailPropsWithStore).chatStore.currentChatData },
				extendInfo:{...chatData.extendInfo||{}},
				showTransCallListKey:Math.random()+'',
				refreshKey:(nextProps as IChatDetailPropsWithStore).chatStore.currentChatData.refreshKey,
				chatSetting: false
			};
		} else {
			return {
				chatId: (nextProps as IChatDetailPropsWithStore).chatStore.currentChatData.id
			};
		}
	}
	scrollTimer: NodeJS.Timeout;
	scrollToBottom = (isSmooth?: boolean) => {
		// console.log('scroll', this.messagesEnd);
		// this.messagesEnd && this.messagesEnd.scrollIntoView(isSmooth?{ behavior: "smooth" }:undefined);
		// setTimeout(()=>{
		// 	this.messagesEnd && this.messagesEnd.scrollIntoView();
		// },500);
		this.scrollTimer && clearTimeout(this.scrollTimer);
		this.scrollTimer = setTimeout(() => {
			if (this.messagesListDom) {
				// console.log('滚动位置',this.messagesListDom.scrollHeight,this.messagesListDom.clientHeight)
				//this.messagesListDom.scrollTop = this.messagesListDom.scrollHeight - this.messagesListDom.clientHeight + 10;
				const lastMessage = this.messagesListDom.lastElementChild;
				if( lastMessage ){
					lastMessage.scrollIntoView({ behavior: "smooth", block: "end" });

				}
				this.preScrollTop = 0;
			}
		}, 10)
		// },50)
	};
	addTagGroup = (userId:string, tagName:string) => {
		this.injected.tagGroupStore.addTagGroup(userId, tagName);
	}
	updateTagGroup = (userId:string, tagNames:string[], sync:boolean = false) => {
		this.injected.tagGroupStore.updateTagGroup(userId, tagNames, sync );
	}
	removeTagGroup = (userId:string, tagName:string)=>{

	}
	addUserMentionUser = (memId: string, name: string) => {
		chatContentCber.changeCallBack(callBackServicetype.chatContent, '@' + name + ' ')
		this.addMentionUser(memId, name, true);
	};

	addMentionUser = (memId: string, name: string, isAddContent?: boolean) => {
		const groupId = this.injected.chatStore.currentChatData[mentionsAllKey];
		if (memId == groupId) {
			this.setState({
				mentionPeople: [{ memId, name }]
			});
			isAddContent && chatContentCber.changeCallBack(callBackServicetype.chatContent, '@' + name + ' ')
			return;
		} else {
			const mentionAll = this.state.mentionPeople.findIndex((item) => item.memId == groupId);
			if (mentionAll > -1) {
				this.setState({
					mentionPeople: [{ memId, name }]
				});
				isAddContent && chatContentCber.changeCallBack(callBackServicetype.chatContent, '@' + name + ' ')
			} else {
				this.setState((state) => ({
					mentionPeople: [...state.mentionPeople, { memId, name }]
				}));
			}
		}
	};
	getMessageStatus = (mesId: string) => {
		const status = this.injected.chatStore.messageStatus.get(mesId);
		return this.injected.chatStore.messageStatus.get(mesId)
	}

	onTransmits = (chats:SelectItemType[])=>{
		this.injected.chatStore.updateTransmitTargets(chats);
	}
	transmitMes: (chats: SelectItemType[]) =>  void;

	getTransmitSubmit = (isSingle: boolean, mes?: MessageItem) => {
		const _hideFunc = this.hideTransmit;
		return (chats: SelectItemType[]) => {
			_hideFunc();
			if (!mes) {
				this.injected.chatStore.switchShowMesSel();
			}
			this.injected.chatStore.transmitMes(isSingle, mes, chats);
		}
	}
	transmitMesEdit = (isSingle: boolean, _message?: MessageItem) => {
		if (Array.from(this.injected.chatStore.selectedMes.values()).length < 1 && !_message) {
			message.warn('请选择一项消息');
			return;
		}
		this.setState({
			showSelectChatModal: true
		})
		this.transmitMes = this.getTransmitSubmit(isSingle, _message ? _message : undefined);

	}
	hideTransmit = () => {
		this.setState({
			showSelectChatModal: false
		})
	}
	imgInput: HTMLInputElement | null;
	changeImg = async (e: React.ChangeEvent<HTMLInputElement>) => {

		if (e.target.files && e.target.files.length > 0) {
			const fileImg = e.target.files[0];
			let imgPath = fileImg.path;
			imgPath = imgPath.replace("\\\\", "\/\/");
			imgPath = imgPath.replace("\\", "\/");
			imgPath = imgPath.replace("\\", "\/");

			this.setState({
				// imgurl: imgPath,
				showMenu: false,

			})
			systemStore.backImageurl = imgPath;
			// let loginDataTemp: any = {};
			// loginDataTemp.backImageurl=imgPath;
			ipcRender.setCookies('backImageurl', imgPath);
		}
	};
	showContentDom = () => {

		this.setState({
			showMenu: false
		})
	}
	isBottom = false;
	setScrollBottom = (isBootm: boolean) => {
		this.isBottom = isBootm;
		this.injected.chatStore.setListIsBottom(isBootm);
	}
	preScrollTop = 0;
	listScrolll = (event: React.UIEvent<HTMLDivElement>) => {
		if (this.messagesListDom) {
			// console.log(this.messagesList.scrollHeight,this.messagesList,this.messagesList.scrollTop,
			// 	this.messagesList.offsetHeight,
			// 	this.messagesList.clientHeight
			// 	);
			const scrollTop = this.messagesListDom.scrollTop;
			const scrollHeight = this.messagesListDom.scrollHeight;
			const clientHeight = this.messagesListDom.clientHeight;
			// console.log('本地消息获取置顶',scrollTop,this.state.getMesLoading,this.preScrollTop)
			if (scrollTop <= 2 && !this.state.getMesLoading && scrollTop < this.preScrollTop) {
				// if(scrollTop <= 20 && !this.state.getMesLoading ){
				let currentMessageList = this.injected.chatStore.messageData.get(this.injected.chatStore.currentChatData.id + '');
				currentMessageList = currentMessageList ? currentMessageList : [];
				if (currentMessageList.length > 0) {
					this.getMoreMessages(Number(currentMessageList[0].timeSend));
					// this.messagesList && this.messagesList.scrollTo(0,70*5)
				}
				this.setScrollBottom(false);
			}
			console.log('scrollTopBottom')
			if (this.messagesListDom.scrollTop + 40 > scrollHeight - clientHeight) {
				this.setScrollBottom(true);
			} else {
				this.setScrollBottom(false);
			}
			this.preScrollTop = scrollTop;
		}
	}
	newTime: number = 0;
	currentId: string = '';
	messageOldFirstId: string = '';
	// 修改chatId 此时没有渲染完消息列表 需要加载完消息列表再置底
	changeChatNeedBottom = false;
	componentDidUpdate(preProps: IChatDetailPropsWithStore) {
		this.updateCallBack();
	}
	
	updateCallBack = () => {
		// console.log('消息列表渲染更新完');
		const mesList = this.injected.chatStore.messageData.get(this.injected.chatStore.currentChatData.id + '');
		let needScrollBottom = false;
		if (this.currentId != this.injected.chatStore.currentChatData.id) {
			// console.log('修改会话列表');
			// needScrollBottom = true;

			this.changeChatNeedBottom = true;
			// this.hasNextPage = true;
		} else if (
			mesList
			&& mesList.length > 0
			&& mesList[mesList.length - 1]
		) {
			// console.log('判断收消息是否置底',mesList[mesList.length - 1].timeSend,this.newTime,this.isBottom)
			if (Number(mesList[mesList.length - 1].timeSend) != this.newTime
				&& this.isBottom
			) {
				// console.log('修改是否底部',this.isBottom);
				// console.log('修改了最后一条消息时间');
				needScrollBottom = true;
			}
			this.newTime = Number(mesList[mesList.length - 1].timeSend);
		}
		if (mesList && mesList.length > 0 && mesList[0]) {
			if (mesList[0].messageId != this.messageOldFirstId) {
				if (this.changeChatNeedBottom) {
					needScrollBottom = true;
					this.changeChatNeedBottom = false
				}
				// console.log('修改了聊天消息');
			}
			this.messageOldFirstId = mesList[0].messageId;
		} else {
			this.messageOldFirstId = '';
		}
		this.currentId = this.injected.chatStore.currentChatData.id;
		needScrollBottom && this.scrollToBottom();

	}
	hasNextPage = true;

	getMoreMessages = async (time: number) => {
		this.setState({
			getMesLoading: true
		});
		const { chatStore } = this.injected;
		const dataChat = chatStore.currentChatData;
		const isGroup = dataChat.type == ChatGrOrFrType.group;
		const listGet = this.injected.chatStore.messageData.get(this.injected.chatStore.currentChatData.id + '');
		const list = listGet ? listGet : [];
		if (list.length > 0) {
			const startTime = list[0].timeSend;
			const { hasMore, amount } = await this.injected.chatStore.getChatMessages(
				this.injected.chatStore.currentChatData.id,
				startTime,
				isGroup,
				undefined,
				undefined,
				this.injected.chatStore.currentChatData.gid
			);
			console.log('获取是否还有数据', hasMore);
			// this.hasNextPage = hasMore;
			if (this.messagesListDom) {
				// this.messagesList.scrollTo(0,amount)
				// console.log('获取数据条数', amount);
				setTimeout(() => {
					this.messagesListDom && this.messagesListDom.scrollTo(0, 75.77 * amount);
				}, 200)
			}
		}
		this.setState({
			getMesLoading: false
		});
	};
	messagesListDom: HTMLDivElement | null;
	drawerType: DrawerType = DrawerType.friend;
	messagesEnd: HTMLDivElement | null;
	transmitCall = async ( serviceId, remark?:string ) => {
		const {chatStore} = this.injected;
		const currentUser = chatStore.currentChatData
		const ret = await imsdk.chat.transferChat(currentUser.id+'', serviceId+'', remark);

		this.injected.chatStore.reloadServicedChats();
		if( ret.resultCode ==1 ){
			chatStore.removeMessageCustomerService(serviceId,0)
			message.success('转接成功');
			return true;
		}else{
			message.info(ret.resultMsg);
		}
		return false;
	}
	isGroup = () => {
		return this.injected.chatStore.currentChatData.type == ChatGrOrFrType.group;
	}
	// getTransCallList = () => {
	// 	const  {chatStore} = this.injected;
	// 	if( chatStore.isLoadingService  ){
	// 		return <div  className="trans-user-item-wrapper"><Spin indicator={<Icon type="loading" style={{ fontSize: 24 }} spin />} /></div>
	// 	}
	// 	return <div className="trans-user-item-wrapper">
	// 		{
	// 			this.injected.chatStore.transCallList.map((item:Department,index)=>{
	// 				return <div>
	// 					<div className='user-name'>{ item.departName }</div>
	// 					<div>
	// 						{
	// 							(item.employees ||[]).map(item=>{
	// 								const isMe = item.userId == systemStore.user.userId;
	// 								return <>
	// 								<div key={index} className={`trans-user-item ${isMe?'trans-user-item-disable':''}`} onClick={()=>{
	// 									if( isMe) return;
	// 									if( !item.onlinestate ){
	// 										message.error('当前客服不在线')
	// 										//return;
	// 									}

	// 									this.transmitCall(item)
	// 									this.setState({
	// 										showTransCallList:false
	// 									})
	// 								}}>
	// 									<AvatorWithPhoto style={{width:'32px',flexShrink:0}} onlineStyle={'dot'} type={item.type} id={item.id} classN="head" onlinestate={item.onlinestate}  />
	// 									<span className='name'>{ item.name || item.nickname }{ isMe?'(我)':''} </span>
	// 								</div>
	// 								</>
	// 							})
	// 						}
	// 					</div>
	// 				</div>
					 
	// 			})
	// 		}
	// 	</div>
		
	// }
	public render() {
		// console.log('更新了')
		const { chatStore, groupStore, tagGroupStore,systemStore } = this.injected;
		let dataChat = chatStore.currentChatData;
		// 当前分流后的真实客服用户ID
		let serviceUserId = Number(dataChat.dynamicServiceUserId)
		/** 公众号ID */
		let serviceId = 0;


		// 当前接待中的用户ID
		let toServicedUserId = 0;

		let service = chatStore.messageCustomerServiceMap.get(dataChat.id+'')
		if( !service && dataChat.dynamicId ){
			service = chatStore.messageCustomerServiceMap.get(dataChat.dynamicId+'')
		}
		if( service ){
			if( dataChat.id  == service.serviceId+''){
				// 聊天公众号和当前环境接待公众号一致
				serviceUserId = service.userId
				serviceId = service.serviceId
			}
		}else{
			// 客服端
			const chatId = dataChat.id;
			
			const servicedUser = chatStore.servicesChats.find(item=> {
				return item.id == dataChat.id
				// if( systemStore.user.isService()){
				// 	// 如果是客服端，
				// 	return item.isServicingUserId == dataChat.id;
				// }else{
				// 	return item.id == dataChat.id
				// }
			});
			if( servicedUser){
				serviceUserId = systemStore.user.userId;
				serviceId = Number(systemStore.officialUserInfo.userId)
			}
		}
		if( isNaN(Number(serviceUserId))){
			serviceUserId = 0;
		}
		// if( dataChat.userType == UserType.Enterprise ){
		// 	const service = chatStore.messageCustomerServiceMap.get(dataChat.id+"")
		// 	if( service ){
		// 		serviceUserId = service.userId
		// 	}
			
		// }
		// if( systemStore.user.isService()){
		// 	const chatCurrent = chatStore.getCurrentChat('service');
		// 	if( chatCurrent ){
		// 		//debugger
		// 	}
		// }
		const isGroup = dataChat.type == ChatGrOrFrType.group;
		const groupMemList = groupStore.groupMemberList.get(dataChat.id);
		const grouptimeTalk = chatStore.groupControlState.get('msgTalkTime');
		// let groupInfo =this.injected.groupStore.getGroupByJid(dataChat.id);
		let list: any = (dataChat && dataChat.id && chatStore.currentChat && (dataChat.id == chatStore.currentChat.id)) ? chatStore.messageListInLimit : [];
		
		// let set = new Set(list.map((item: any) => { return item.messageId }));
		// console.log(set.size, set);
		let timeTalk;
		let chatRole = dataChat.role;
		if (groupMemList) {
			groupMemList.forEach(item => {
				if (item.userId == systemStore.userId) {
					timeTalk = item.talkTime;
					if (!dataChat.role) {
						chatRole = item.role
					}
				}
			});
		}
		// console.log('渲染是否禁言',isGroup,dataChat);
		const isForbitGr =
			isGroup &&
			chatRole &&
			chatRole != GroupMemRole.owner &&
			chatRole != GroupMemRole.manage


	    const forbitContent = isForbitGr&&(grouptimeTalk && Number(grouptimeTalk) > 0) ?"全员禁言中":(isForbitGr&&(timeTalk && Number(timeTalk) > 0) ? '你已被禁言' : '');
		const canViewInfo = Boolean(
			chatRole == GroupMemRole.owner || chatRole == GroupMemRole.manage || !dataChat.allowFriends
		);
		const isSnap = dataChat.snapChat && dataChat.snapChat > 0;

		if (systemStore.isDelAfterReading == 1 && isSnap) {
			chatStore.setSnapChat(dataChat.id, 0);
			// this.setSnapChat(0);
		}

		// const menuDom = (
		// 	<div className="send-list">
		// 		<label className="item" >
		// 			<span>更换背景</span>
		// 			<input
		// 				type="file"
		// 				ref={ref => this.imgInput = ref}
		// 				accept="image/png,image/jpeg,image/gif"
		// 				style={{ display: 'none' }}
		// 				onChange={this.changeImg}
		// 			>
		// 			</input>
		// 		</label>
		// 	</div>
		// );
		var sectionStyle = {
			backgroundImage: `url(${systemStore.backImageurl})`,
			backgroundSize: "cover",
			padding: '12px 16px 0 16px'
		};
		const loginLog =this.chatDetail.loginLog ||{}
		const loginDevice = loginLog.model ? loginLog.model :loginLog.appBrand;
		const loginTime = loginLog.loginTime ? Utils.toDateTimeFormat(Number(loginLog.loginTime), "YYYY-MM-DD HH:mm"):''
		const address = this.chatDetail.ipAnalysisVO? this.chatDetail.ipAnalysisVO.address : ''
		const tagGroupChildren = [];
		(tagGroupStore.groupList||[]).forEach(item=>{
			tagGroupChildren.push(<Select.Option key={item.name} value={item.name}>{item.name}</Select.Option>)
		});
		console.log("value-taggroups",this.state.tagsGroup, this.chatDetail)
		return (
			<div className="chat-detail-body chat-detail">
				<div className={dataChat.isBacklock ? 'forbit' : ''}>{dataChat.isBacklock ? "此群已被锁定" : ''}</div>
				<div className="chart-header">
					<div className="dragbox"></div>
					<div className="dragbox-close-area"></div>
					<div className="left-wraper">
						{/* <span>usertype:{dataChat.userType}</span> */}
						<Icon type="left" className="back-but" onClick={chatStore.detailBack} />
						<AvatorWithPhoto style={{width:'32px',flexShrink:0}} onlineStyle={'dot'} userType={dataChat.userType} type={dataChat.type} id={dataChat.id} classN="head" onlinestate={dataChat.onlinestate}  />
						<div className="right-name">
							<div className="chat-name">
								{isGroup ? dataChat.name : dataChat.remarkName ? dataChat.remarkName : dataChat.name}
							</div>
							<div className='status-group'>
								{ !this.isGroup() ? <div className="info">
									<span style={{marginRight:'5px',whiteSpace:'nowrap',fontSize:'12px'}}>客户标签</span>
									{ 
										<TagViewer tags={dataChat.tagGroups||[] as any}></TagViewer>
									}
									
									{/* <Tag color="red">高风险</Tag> */}
									
									{ this.state.editingTagGroup ? 
										<TagSelector childrenValues={
											tagGroupStore.groupList||[].map(item=>{
											return {
												value: item.name,
												name: item.name
											}
										}) as any
									} values={ (dataChat.tagGroups||[]).map(item=> 
										{
											return {
												value: item.name,
												name:item.name
											}
										}
										)}

										onDropdownVisibleChange ={(visible)=>{
											if(!visible){
												this.updateTagGroup(dataChat.id, this.state.tagsGroup, true)
												// this.setState({
												// 	tagsGroup:(dataChat.tagGroups||[]).map(item=> item.name)
												// })
												this.setState({
													editingTagGroup:false
												})
											}	
										}}
										
										onChange={(value)=>{
											this.setState({
													tagsGroup: value
												})
												this.updateTagGroup(dataChat.id, value, false )
										}}
										></TagSelector>:
										<div className="status-text" onClick={()=>{
										this.setState({
											editingTagGroup:true
										})
									}}>
										{/* <span>{dataChat.desc}</span> */}
										
										<Icon type="edit" />
										</div> }
									
								</div>
								:null}
							</div>
							
							
						</div>
					</div>
					<div className="chat-detail-headbut-wrap">
						{/* 隐藏原群公告入口图标 */}
						{/* {isGroup ? (
							<IconImgEdit
								onClick={() => this.showChatNotice()}
								img={require('../../assets/image/notice-icon.png')}
								size={20}
								classN="chat-detail-icon"
							/>
						) : null} */}
						<>
							<Modal
								title="转接会话"
								cancelText="取消"
								okText="确认转接"
								onCancel={()=>{
									this.setState({
										showTransCallList:false
									})
								}}
								onOk={()=>{
									if( this.state.transUserId ){
										if( this.state.transUserId == systemStore.user.userId ){
											message.error('不能转接自己')
											return;
										}
										this.transmitCall(this.state.transUserId, this.state.transUserRemark).then( success=>{
											if(success){
												this.setState({
													isInservicing:false
												})
											}
										})
										this.setState({
											showTransCallList:false,
										})
									}else{
										message.error('未知错误')
									}
								}}
								visible={this.state.showTransCallList}
								width={645}
							>
								<SelectService reload={this.state.showTransCallList} onChange={({userId,remark})=>{
									this.setState({
										transUserId:userId,
										transUserRemark:remark
									})
								}}></SelectService>
							</Modal>
		
				
							<span  className="chat-more-but">
								{ 
									this.canTransCall()? 
										<Tooltip title='转接客服'> 
											<span className="icon" onClick={() => {
												this.setState({
													showTransCallList:true
												})
											}}>
												<SvgIcon name="recall" size='16'></SvgIcon>
												{/* <span>转接</span> */}
											</span>
										</Tooltip>
									  
									
									
									
									:null 
								}
								{
									!this.isUserService()?
									<IconImgEdit
									img={
										isSnap ? (
											require('../../assets/image/time_icon.png')
										) : (
												require('../../assets/image/dian.png')
											)
									}
									size={14}
									marginSize={isSnap ? 0 : 16}
									classN="chat-detail-icon"
									onClick={() => {
										this.showChatSetting(isGroup)
									}}
								/>:null
								}
								
								
								<span>{isSnap ? Utils.getDeadLineTime(dataChat.snapChat || 1).name : null}</span>
							</span>
						
						</>
					</div>
				</div>

				<DrawerDetail
					isshow={this.state.chatSetting}
					canViewInfo={canViewInfo}
					onclose={this.onClose}
					drawerType={this.drawerType}
					groupId={
						dataChat.gid ? (
							dataChat.gid + ''
						) : (
								'5d0f54f4d95e634aa95f3b5b'
							)
					}
				/>
				{/* <Popover
					placement="top"
					content={menuDom}
					trigger="contextMenu"
					visible={this.state.showMenu}
					// onVisibleChange={(isShow: boolean) => this.setState({ showMenu: isShow })}
				> */}
				<div className='messages-container'>
					<div className='messages-body-container'>
						<div className="messages-body" ref={ref => this.messagesListDom = ref} onScroll={this.listScrolll} style={sectionStyle} onClick={this.showContentDom}>
							
							{
								this.state.getMesLoading && !this.injected.chatStore.loadingChatDetailData
									? <Spin />
									: null
							}
							{
								/*this.injected.chatStore.loadingChatDetailData
									? (
										<div className="loading-wrap">
											<Spin tip="消息加载中..." />
										</div>
									)
									: null*/
							}
							{/* {msgs &&
									msgs.map((message: MessageItem, index: number) => {
										return (
											<MessageItemView
												canViewInfo={canViewInfo}
												reSendMes={this.reSendMes}
												key={index + message.messageId}
												keyIndex={index + message.messageId}
												message={message}
												messageStatus={chatStore.messageStatus.get(message.messageId)}
												isGroup={isGroup}
												role={dataChat.role ? dataChat.role : GroupMemRole.member}
												addmentionUser={this.addUserMentionUser}
											/>
										);
									})
								} */}
							<MessageList
								canViewInfo={canViewInfo}
								reSendMes={this.reSendMes}
								messageStatus={this.getMessageStatus}
								isGroup={isGroup}
								isForbidden={Boolean(isForbitGr&&((grouptimeTalk && Number(grouptimeTalk) > 0)||(timeTalk && Number(timeTalk) > 0)))}
								role={dataChat.role ? dataChat.role : GroupMemRole.member}
								addUserMentionUser={this.addUserMentionUser}
								transmitMes={this.transmitMesEdit}
								listForceScroll={this.state.listForceScroll}
								list={list}
								updateCallBack={this.updateCallBack}
								currentChatType={dataChat.userType}
								currentChatid={dataChat.id}
								toServicedUserId={toServicedUserId}
							/>
							
						</div>
						{/* </Popover> */}
						<div className="chat-send-box">
							<SendBoard
								isMesSel={this.injected.chatStore.isMesSel}
								isForbit={Boolean(isForbitGr&&((grouptimeTalk && Number(grouptimeTalk) > 0)||(timeTalk && Number(timeTalk) > 0)))}
								forbitContent={forbitContent}
								isGroup={isGroup}
								groupMemList={groupMemList ? groupMemList : new Map()}
								sendContent={this.send}
								updateChatData={this.updateChatData}
								friendList={this.injected.friendStore.friendList}
								addmentionUser={this.addMentionUser}
								groupId={dataChat[mentionsAllKey]}
								chatId={dataChat.id}
								transmitMes={this.transmitMesEdit}
								
								serviceUserId={serviceUserId}
								serviceId={serviceId}
								cancelTransmit={this.injected.chatStore.switchShowMesSel}
								chatRole={chatRole ? chatRole : GroupMemRole.member}
							/>
						</div>
						<Modal visible={this.state.showSelectChatModal}
							title="转发"
							cancelText="取消"
							okText="确定"
							onCancel={() => {
								this.setState({
									showSelectChatModal: false	
								})
							}}
							onOk={()=>{
								//this.transmitMes()
								this.transmitMes( this.injected.chatStore.transmitTargets )
								this.injected.chatStore.updateTransmitTargets([])
							}}
						>
							
							<TransmitSelectModal submitTransmit={this.onTransmits} />
						</Modal>
						{/* {
							this.state.showSelectChatModal
								? <TransmitSelectModal submitTransmit={this.transmitMes} />
								: null
						} */}
						{
							Array.isArray(chatStore.transmitMesList) && chatStore.transmitMesList.length > 0
								? <MesListModal mesList={chatStore.transmitMesList} submitOk={chatStore.hideTransmitmes} />
								: null
						}
					</div>
					{
						this.showInfo() && !isGroup && (
							<div className="message-body-userinfo" ref={this.refMessageBodyUserInfo}>
								<ResizeBar
									horizontal={false}
									target={this.refMessageBodyUserInfo}
									minSize={170}
									maxSize={240}
									position='right'
									></ResizeBar>
								<Tabs defaultActiveKey="user1" onChange={()=>{

								}}>
									<TabPane tab="用户信息" key="user22">
										<div className="info-wrapper">
											<h3>访问信息</h3>
											<div className='info-content'>
												<div className='line'><span className='label'>登录地区</span><em>{ address }</em></div>
												<div className='line'><span className='label'>登录设备</span><em>{ loginDevice }</em></div>
												<div className='line'><span className='label'>登录IP</span><em>{this.chatDetail.loginIp||''}</em></div>
												
												
												<div className='line'><span className='label'>登录记录</span><em className='mark'>{this.chatDetail.loginLogCount||''}</em></div>
												<div className='line'><span className='label'>同IP用户</span><em className='mark'>{this.chatDetail.sameIpCount||''}</em></div>
												<div className='line'><span className='label'>最后上线</span><em>{loginTime||''}</em></div>
											</div>
											<h3>注册信息</h3>
											<div className='info-content'>
												<div className='line'><span className='label'>用户ID</span><em>{this.chatDetail.account }</em></div>
												<div className='line'><span className='label'>用户昵称</span><em>{this.chatDetail.nickname ||''}</em></div>
												
												<div className='line'><span className='label'>联系方式</span><em>{this.chatDetail.telephone||''}</em></div>
												
												
											</div>
											<h3>备注信息</h3>
											<div className='info-content'>
												<div className='line'><span className='label'>姓名</span>
												<InputQuickEditor onUpdate={(value)=>{
														
														
														this.updateChatDetail('name',value)
														//this.chatDetail.name = value;
													}} style={{'width':'100px'}} value={this.state.extendInfo.name}>
													 <em>{this.state.extendInfo.name ||''}</em>
													</InputQuickEditor>
												</div>
												<div className='line'><span className='label'>备用电话</span>
													<InputQuickEditor onUpdate={(value)=>{
														this.updateChatDetail('phone',value)
														//this.chatDetail.phone = value
														//this.updateChatDetail('phone',value)
													}} style={{'width':'100px'}} value={this.state.extendInfo.phone}>
														<em>{this.state.extendInfo.phone||''}</em>
													</InputQuickEditor>
												</div>
												
												<div style={{marginTop:'5px'}}><TextArea placeholder='请输入备注信息' value={this.state.extendInfo.remark} onChange={(e)=>{
													
													this.updateChatDetail('remark',e.target.value)
													// this.updateChatRemark({
													// 	userId:this.chatDetail.userId,
													// 	remark:e.target.value
													// })
												}}
												onBlur={(e)=>{
													this.updateChatDetail('remark',e.target.value)
													// this.updateChatRemark({
													// 	userId:this.chatDetail.userId,
													// 	remark:e.target.value
													// })
												}}
												></TextArea></div>
											</div>
										</div>
									</TabPane>
									{/* <TabPane tab="IP信息" key="location">
									<div className="info-wrapper">
											<h3>IP信息</h3>
											<div className='info-content'>
												<div>IP：{this.chatDetail.loginIp||''}</div>
											</div>
										</div>
									</TabPane> */}
									
								</Tabs>
							</div>
						)
					}
					
				</div>
				

			</div>

		);
	}
}
